<?php

namespace App\Http\Controllers\Mp;

use App\Contract\ContractStatus;
use App\Http\Controllers\Controller;
use App\Model\Bill;
use App\Model\House;
use App\Utils\Result;
use Carbon\Carbon;
use Illuminate\Http\Request;

class StatController extends Controller
{
    public function index(Request $request)
    {
        $days = $request->input('days');

        // 最近一年收入统计
        $data = [
          'label' => [],
          'data' => [
              [],
              []
          ]
        ];

        $date = Carbon::now()->subDays($days - 1);
        for ($i = 0; $i < $days; $i ++) {
            $bill = Bill::query()->where('business_id', $this->getBusinessId())
                ->whereDate('paid_at', $date->toDateString())
                ->sum('amount');
            $paid = Bill::query()->where('business_id', $this->getBusinessId())
                ->whereDate('paid_at', $date->toDateString())
                ->where('is_paid', 1)
                ->sum('amount');

            if ($bill OR $paid) {
                $data['label'][] =  $date->month . '/' . $date->day;
                $data['data'][0][] = $bill;
                $data['data'][1][] = $paid;
            }

            $date->addDay();
        }

        $bills = Bill::query()->where('business_id', $this->getBusinessId())
            ->where('paid_at', '>=', Carbon::now()->subDays($days)->toDateString() . ' 00:00:00')
            ->where('is_paid', 1)
            ->with('billPay')
            ->orderByDesc('paid_at')
            ->get();

        foreach ($bills as &$item) {
            $item->pay_date = Carbon::createFromFormat('Y-m-d H:i:s', $item->paid_at)->toDateString();
        }

        return Result::success([
            'bill' => $data,
            'bills' => $bills,
            'house' => []
        ]);
    }
}
